package com.yzt.minemodule.activity;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.yzt.zhuju.RXingUtils;
import com.yzt.zhuju.arouter.RouterAccount;
import com.yzt.zhuju.arouter.RouterMessage;
import com.yzt.zhuju.arouter.RouterUser;
import com.yzt.zhuju.base.BaseActivity;
import com.yzt.zhuju.dialog.MenuSelectDialog;
import com.yzt.zhuju.network.AresSubscriber;
import com.yzt.zhuju.network.biz.BizLayer;
import com.yzt.zhuju.network.entity.user.FollowUserStatusRequest;
import com.yzt.zhuju.network.entity.user.PersonalDetailBasic;
import com.yzt.zhuju.photoview.PhotoViewManager;
import com.yzt.zhuju.utils.AppDialogUtil;
import com.yzt.zhuju.utils.PersonalDetailCacheManager;
import com.yzt.zhuju.utils.ViewUtil;
import com.yzt.zhuju.utils.ViewUtils;
import com.yzt.zhuju.voice.VoicePlayManager;
import com.yzt.zhuju.widget.PageIndicatorView;
import com.yzt.zhuju.widget.tuiview.TUILinearLayout;
import com.yzt.zhuju.widget.tuiview.TUITextView;
import com.yzt.zhuju.widget.widget.ImageLoadManger;
import com.yzt.minemodule.R;
import com.yzt.minemodule.banner.BannerViewHolder;
import com.yzt.minemodule.fragment.UserActivityFragment;
import com.yzt.minemodule.fragment.UserDynamicFragment;
import com.yzt.p_base.AppUtils;
import com.yzt.plugin_imageloader.ImageLoadUtil;
import com.yzt.plugin_network.response.HttpResponse;
import com.yzt.plugin_widget.RoundImageView;
import com.yzt.plugin_widget.tableBar.SlidingTabLayout;
import com.yzt.plugin_widget.viewPager.ViewPagerAdapter;
import com.opensource.svgaplayer.SVGAImageView;
import com.zhouwei.mzbanner.MZBannerView;
import com.zhouwei.mzbanner.holder.MZHolderCreator;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.jzvd.Jzvd;

/**
 * author : bob
 * date   : 2022/12/7
 * desc   : 用户详情页面
 */
@SuppressLint("SetTextI18n")
@Route(path = RouterUser.ACTIVITY_PERSONAL_DETAIL)
public class PersonalDetailActivity extends BaseActivity {

    @Autowired
    String mUserId;

    @Autowired
    int type;

    private Toolbar toolbar;

    /**
     * 顶部标签
     */
    private ImageView mTitleLeftIv;
    private ImageView mTitleMoreIv;

    /**
     * 轮播图
     */
    private MZBannerView<String> bannerView;
    private PageIndicatorView indicatorView;

    /**
     * 昵称 访客
     */
    private TextView mTvName;

    /**
     * 标题栏昵称
     */
    private TextView textViewTopNickName;

    /**
     * 签名
     */
    private TextView tvDesc;

    private RoundImageView imgAvatar;
    private TextView followCount;
    private TextView fansCount;
    private TextView friendCount;
    private TextView likeCount;

    private TUITextView tvGender;
    private TUITextView tv_constellation;

    private TUITextView tvChat;
    private TUITextView tvFollow;
    private TUITextView tvFollowed;
    private TUILinearLayout tvFollowEach;

    private SVGAImageView svgaPersonalHomeDecoration;

    private PhotoViewManager photoViewManager;

    private final List<String> albums = new ArrayList<>();

    private PersonalDetailBasic mPersonalDetail;

    @Override
    public int getLayoutId() {
        return R.layout.activity_person_detail;
    }

    /**
     * 获取状态栏高度
     */
    private void initTitleContainerMargin() {
        RelativeLayout rlTitleContainer = findViewById(R.id.person_title_layout);
        Toolbar.LayoutParams ll = (Toolbar.LayoutParams) rlTitleContainer.getLayoutParams();
        ll.setMargins(0, ViewUtils.getStatusBarHeight(this), 0, 0);
        rlTitleContainer.setLayoutParams(ll);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void installViews() {

        setFullScreen(true);

        initTitleContainerMargin();

        photoViewManager = PhotoViewManager.getInstance(AppUtils.getApp());

        // 顶部昵称
        textViewTopNickName = findViewById(R.id.textViewTopNickName);

        // 标题容器
        mTitleLeftIv = findViewById(R.id.title_left_iv);

        // 昵称 在线 id
        mTvName = findViewById(R.id.tvPersonName);
        imgAvatar = findViewById(R.id.img_avatar);
        followCount = findViewById(R.id.tv_follow_count);
        fansCount = findViewById(R.id.tv_fans_count);
        friendCount = findViewById(R.id.tv_friend_count);
        followCount.setOnClickListener(this);
        fansCount.setOnClickListener(this);
        friendCount.setOnClickListener(this);
        findViewById(R.id.tv_follow_count1).setOnClickListener(this);
        findViewById(R.id.tv_fans_count1).setOnClickListener(this);
        findViewById(R.id.tv_friend_count1).setOnClickListener(this);
        likeCount = findViewById(R.id.tv_like_count);
        tvGender = findViewById(R.id.tv_gender);
        tv_constellation = findViewById(R.id.tv_constellation);

        // 签名
        tvDesc = findViewById(R.id.tv_user_desc);

        // 页面滑动监听
        loadScrollView();

        // 初始轮播图
        initBannerView();

        // 初始化上下监听
        initListener();

        // 缓存数据
        getHttpData();

        initViews();
    }

    private SlidingTabLayout mTabLayout;

    private ViewPager mViewPager;

    /**
     * 加载页面分类
     */
    private void initViews() {
        mTabLayout = findViewById(R.id.tablayout);
        mViewPager = findViewById(R.id.viewPager);
        List<String> tabs = new ArrayList<>();
        List<Fragment> fragments = new ArrayList<>();
        tabs.add("活动");
        tabs.add("动态");
        fragments.add(UserActivityFragment.getInstance(mUserId));
        fragments.add(UserDynamicFragment.getInstance(mUserId));
        mViewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager(), fragments, tabs));
        mViewPager.setOffscreenPageLimit(tabs.size());
        mTabLayout.setViewPager(mViewPager);
    }

    /**
     * 页面滑动处理
     */
    private void loadScrollView() {

        toolbar = findViewById(R.id.toolbar);

        NestedScrollView scrollView = findViewById(R.id.scrollView);

        scrollView.setOnScrollChangeListener((NestedScrollView.OnScrollChangeListener) (v, scrollX, scrollY, oldScrollX, oldScrollY) -> {

            int offsetHeight = 300;

            if (scrollY > offsetHeight) {
                toolbar.setBackgroundColor(ContextCompat.getColor(PersonalDetailActivity.this, R.color.white));
                mTitleLeftIv.setImageResource(R.mipmap.icon_back_black);
                mTitleMoreIv.setImageResource(R.mipmap.icon_title_more_black);
                textViewTopNickName.setTextColor(ContextCompat.getColor(this, R.color.color_262628));
                textViewTopNickName.setVisibility(View.VISIBLE);
            } else {
                toolbar.setBackgroundColor(changeAlpha(ContextCompat.getColor(PersonalDetailActivity.this, R.color.white),
                        Math.abs(scrollY * 1.0f) / offsetHeight));
                mTitleLeftIv.setImageResource(R.mipmap.icon_back_white);
                mTitleMoreIv.setImageResource(R.mipmap.icon_title_more);
                textViewTopNickName.setTextColor(Color.WHITE);
                textViewTopNickName.setVisibility(View.GONE);
            }
        });
    }

    /**
     * banner栏
     */
    private void initBannerView() {
        indicatorView = findViewById(R.id.indicator);
        bannerView = findViewById(R.id.banner_view);
        bannerView.setIndicatorRes(R.drawable.shape_indicator_selected, R.drawable.shape_indicator_normal);
        bannerView.setIndicatorAlign(MZBannerView.IndicatorAlign.CENTER);
        bannerView.setBannerPageClickListener((view, position) -> {
            if (albums == null || albums.size() == 0) {
                return;
            }
            List<String> list = new ArrayList<>();
            List<String> newList = new ArrayList<>(albums);
            for (String album : newList) {
                list.add(ImageLoadUtil.url2Webp(album));
            }
            newList.clear();
            photoViewManager.showPhotoView(view, list, position);
        });

        bannerView.addPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                indicatorView.setPersonalSelectedPage(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        initAlbum();
    }

    /**
     * 顶部和底部监听注册
     */
    public void initListener() {

        // 返回
        findViewById(R.id.title_left_layout).setOnClickListener(this);

        // 更多 编辑
        mTitleMoreIv = findViewById(R.id.title_more_iv);
        mTitleMoreIv.setOnClickListener(this);
        mTitleMoreIv.setImageResource(R.mipmap.icon_title_more);

        // 私信关注
        tvChat = findViewById(R.id.tv_chat);
        tvFollow = findViewById(R.id.tv_follow);
        tvFollowed = findViewById(R.id.tv_followed);
        tvFollowEach = findViewById(R.id.tv_follow_each);
        tvChat.setOnClickListener(this);
        tvFollow.setOnClickListener(this);
        tvFollowed.setOnClickListener(this);
        tvFollowEach.setOnClickListener(this);
    }

    /**
     * 根据百分比改变颜色透明度
     */
    public int changeAlpha(int color, float fraction) {
        int red = Color.red(color);
        int green = Color.green(color);
        int blue = Color.blue(color);
        int alpha = (int) (Color.alpha(color) * fraction);
        return Color.argb(alpha, red, green, blue);
    }

    /**
     * 获取页面数据
     * 缓存数据 - 网络请求
     */
    public void getHttpData() {
        Map<String, String> map = new HashMap<>();
        map.put("userId", mUserId);
        BizLayer.getInstance().getAccountModule().getFullInfoParts(map, new AresSubscriber<PersonalDetailBasic>() {
            @Override
            protected void onSuccess(PersonalDetailBasic personalDetail) {
                PersonalDetailCacheManager.addPersonalDetail(personalDetail);
                mPersonalDetail = personalDetail;
                try {
                    initData();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 加载相册
     */
    private void initAlbum() {
        indicatorView.setVisibility(albums.size() > 1 ? View.VISIBLE : View.GONE);
        indicatorView.initPersonalIndicator(albums.size());
        bannerView.setIndicatorVisible(false);
        bannerView.setPages(albums, (MZHolderCreator<BannerViewHolder>) BannerViewHolder::new);
        bannerView.setCanLoop(false);
    }

    /**
     * 判断是否是本人
     */
    private boolean isMe() {
        return TextUtils.equals(RXingUtils.getUserId(), mUserId);
    }

    /**
     * 加载用户信息
     */
    public void initData() {

        if (mPersonalDetail.getBgImage() != null) {
            albums.add(mPersonalDetail.getBgImage());
        }

        initAlbum();

        // 头像
        ImageLoadManger.loadIv(mActivity, mPersonalDetail.getAvatar(), imgAvatar, R.mipmap.default_photo);

        // 昵称
        mTvName.setText(mPersonalDetail.getNickName());

        // 粉丝
        followCount.setText(String.valueOf(mPersonalDetail.getFollowNum()));
        fansCount.setText(String.valueOf(mPersonalDetail.getFansNum()));
        friendCount.setText(String.valueOf(mPersonalDetail.getFriendNum()));
        likeCount.setText(String.valueOf(mPersonalDetail.getLikeNum()));

        tvGender.setSelected(mPersonalDetail.getGender() == 1);
        tvGender.setText(mPersonalDetail.getAge() + "岁");
        // 星座
        tv_constellation.setText(mPersonalDetail.getConstellation());
        // 自我介绍
        tvDesc.setText(mPersonalDetail.getIntro());

        // 关注状态:需求上 已经关注、互相关注文案下可以调取取消关注接口 [ 1：关注，2：已关注，3：互相关注，4：回关 ]
        tvFollow.setVisibility(View.GONE);
        tvFollowed.setVisibility(View.GONE);
        tvFollowEach.setVisibility(View.GONE);
        if (mPersonalDetail.getFollowStatus() == 1) {
            tvFollow.setVisibility(View.VISIBLE);
        } else if (mPersonalDetail.getFollowStatus() == 2) {
            tvFollowed.setVisibility(View.VISIBLE);
        } else if (mPersonalDetail.getFollowStatus() == 3) {
            tvFollowEach.setVisibility(View.VISIBLE);
        } else {
            tvFollow.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);

        if (ViewUtil.isFastDoubleClick()) {
            return;
        }

        if (view.getId() == R.id.title_left_layout) {
            // 关闭
            finish();
        } else if (view.getId() == R.id.title_more_iv) {
            // 更多
            if (isMe()) {
                RouterUser.PersonDetailEditActivity(mUserId);
            } else {
                if (mPersonalDetail == null || mUserId == null) {
                    return;
                }
                // 举报弹窗
                MenuSelectDialog menuSelectDialog = new MenuSelectDialog(this, R.style.ActionSheetDialogStyle);
                menuSelectDialog.setLogoutText("拉黑", "举报");
                menuSelectDialog.setOnItemClickListener(i1 -> {
                    if (i1 == 0) {
                        //清除缓存空间
                        AppDialogUtil.showNoTitleDialog(mActivity, "拉黑后将无法查看该用户发布的活动、动态，不会收到对方发来的消息，是否确认？", mActivity.getString(R.string.cancel),
                                mActivity.getString(R.string.sure), new AppDialogUtil.DialogClickInterface() {
                                    @Override
                                    public void onCancelClick() {

                                    }

                                    @Override
                                    public void onSureClick() {
                                        showToast("拉黑缺少接口");
                                    }
                                });
                    }
                    if (i1 == 1) {
                        RouterAccount.ReportActivity(mUserId);
                    }
                });
            }
        } else if (view.getId() == R.id.tv_chat) {
            // 私信
            RouterMessage.ConversationActivity(mUserId, mPersonalDetail.getNickName(), false);
        } else if (view.getId() == R.id.tv_follow) {
            // 关注
            follow(1);
        } else if (view.getId() == R.id.tv_followed) {
            // 已关注
            follow(2);
        } else if (view.getId() == R.id.tv_follow_each) {
            // 互相关注
            follow(2);
        } else if (view.getId() == R.id.tv_follow_count || view.getId() == R.id.tv_follow_count1) {
            RouterUser.FriendListActivity(RouterUser.FriendType.TYPE_FOLLOW,mUserId);
        } else if (view.getId() == R.id.tv_fans_count || view.getId() == R.id.tv_fans_count1) {
            RouterUser.FriendListActivity(RouterUser.FriendType.TYPE_FANS,mUserId);
        } else if (view.getId() == R.id.tv_friend_count || view.getId() == R.id.tv_friend_count1) {
            RouterUser.FriendListActivity(RouterUser.FriendType.TYPE_FRIEND,mUserId);
        }
    }

    private void follow(int type) {
        FollowUserStatusRequest mFollowRequest = new FollowUserStatusRequest();
        List<String> list = new ArrayList<>();
        list.add(mUserId);
        mFollowRequest.setUidRels(list);
        mFollowRequest.setStatus(type);
        BizLayer.getInstance().getAccountModule().postFollowOrUnfollowUser(mFollowRequest, new AresSubscriber<HttpResponse>() {
            @Override
            protected void onSuccess(HttpResponse httpResponse) {
                getHttpData();
            }
        });
    }

    @Override
    public void finish() {
        super.finish();
        if (mPersonalDetail != null) {
            mPersonalDetail = null;
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        Jzvd.goOnPlayOnPause();
        VoicePlayManager.getInstance().stopPlay();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (bannerView != null) {
            bannerView.pause();
        }
        if (svgaPersonalHomeDecoration != null) {
            svgaPersonalHomeDecoration.stopAnimation();
            svgaPersonalHomeDecoration.clear();
            svgaPersonalHomeDecoration = null;
        }
        if (photoViewManager != null) {
            photoViewManager.clear();
            photoViewManager = null;
        }
    }
}